package com.net.url;

import org.junit.Test;

import java.io.*;
import java.net.*;

/**
 * Created by yangliwei on 2017/7/23.
 *
 * url各个参数的解析
 *      http://example.com:80/docs/books/tutorial/index.html?name=networking#DOWNLOADING"
 *
 *      protocol = http
 *      authority = example.com:80
 *      host = example.com
 *      port = 80
 *      path = /docs/books/tutorial/index.html
 *      query = name=networking
 *      filename = /docs/books/tutorial/index.html?name=networking
 *      ref = DOWNLOADIN
 */
public class URLDemo {

    /**
     * 目测URL参数protocal 有ftp, http, nntp,flie
     *
     * 该方法新建一个基于file协议的url连接，
     */
    @Test
    public void testURL(){
        String protocal = "file";
        String host = "127.0.0.1";
        String file = System.getProperty("user.dir");
        try {
            URL url = new URL(protocal,host, File.separator+file);
//            file://127.0.0.1\D:\ideaProject\javaStudy
            System.out.println(url.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 从url中读取数据
     * 写数据类似
     * @throws Exception
     */
    @Test
    public void testRead() throws Exception {
        URL oracle = new URL("https://www.oracle.com/index.html");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }




    //给url设置socks代理
    @Test
    public void socksClient() throws IOException {
        InputStream inputStream  = null;
        try {
            // proxy
            SocketAddress address = new InetSocketAddress("127.0.0.1", 6666);
            Proxy proxy = new Proxy(Proxy.Type.SOCKS, address);
//            Socket client = new Socket(proxy);

            //http
//            SocketAddress httpAddress = new InetSocketAddress("127.0.0.1", 8888);
//            Proxy httpProxy = new Proxy(Proxy.Type.HTTP, httpAddress);
            URL url = new URL("https://www.ietf.org/rfc/rfc1928.txt");
            URLConnection connection= url.openConnection(proxy);
            inputStream = connection.getInputStream();
            InputStreamReader reader = new InputStreamReader(inputStream);
            LineNumberReader lineNumberReader = new LineNumberReader(reader);
            System.out.println(reader.getEncoding()+"  ");
            String temp = null;
            while((temp = lineNumberReader.readLine())!=null){
                System.out.println(temp);
            }
//            Socket httpClient = new Socket(httpProxy);



        }
        catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream!= null){
                inputStream.close();
            }
        }
    }
}
